#include "../shared/NetworkPacket.h"

module GameNodeP
{
	uses interface Timer<TMilli>;
	uses interface Read<uint16_t> as PhotoSensor;
	uses interface AMSend;
	uses interface Receive;
	uses interface Packet;
	uses interface AMPacket;
	uses interface Leds;
	
	uses interface Boot;
	uses interface SplitControl as RadioPowerControl;
}
implementation
{
	uint16_t lastReading = 0;
	message_t buffer;
	uint16_t lightSamplingInterval = 50;
	uint16_t lightReportingInterval = 10;
	uint16_t lightReportingIndex = 0;

	uint16_t lightReportingThreshold = 5;
	
	task void handleReading();

	event void Boot.booted()
	{
		call RadioPowerControl.start();
		call Leds.led2On();
	}
	
	event void RadioPowerControl.startDone(error_t err)
	{
		if(err == SUCCESS){
			call Timer.startPeriodic(lightSamplingInterval);
			call Leds.led1On();
		}
		else
			call RadioPowerControl.start();
	}
	
	event void RadioPowerControl.stopDone(error_t err)
	{
	}
	
	event void Timer.fired()
	{
		lightReportingIndex = (lightReportingIndex + 1) % lightReportingInterval;
		if(lightReportingIndex == 0){
			call PhotoSensor.read();
		}
	}
	
	
	event void PhotoSensor.readDone(error_t err, uint16_t value)
	{
		if(err != SUCCESS)
			call PhotoSensor.read();
		else
		{
			lastReading = value;
			post handleReading();
		}
	}
	
	task void handleReading()
	{
		network_packet_t * payload = (network_packet_t *)call Packet.getPayload(&buffer, NULL);
		payload->data = lastReading;
		payload->type = LIGHT_SENSOR;
/*		call Leds.led1Toggle();	*/
	
		if(call AMSend.send(AM_HUB_ID, &buffer, sizeof(network_packet_t)) != SUCCESS)
			post handleReading();
	}
	
	event void AMSend.sendDone(message_t * msg, error_t err)
	{
		if(err != SUCCESS)
			post handleReading();
	}

	void processPacket(network_packet_t * packet){
		switch(packet->type){
			case LED_COMMAND:
				call Leds.set((uint8_t)packet->data);
				break;
			case SET_SAMPLE_INTERVAL:
				lightReportingInterval = packet->data;
				if(lightReportingIndex >= lightReportingInterval){
					lightReportingIndex = lightReportingInterval - 1;
				}
				break;
		}
	}
	
	event message_t * Receive.receive(message_t * msg, void * payload, uint8_t size)
	{
		if(sizeof(network_packet_t) == size){
			network_packet_t * packet = (network_packet_t *)payload;
		/*	call Leds.led0Toggle();	*/
	
			processPacket(packet);

			return msg;
		}
	}
}
